package com.example.goband.api;

import com.example.goband.Service.UserService;
import com.example.goband.common.AjaxResult;
import com.example.goband.common.AppVariable;
import com.example.goband.common.PasswordUtils;
import com.example.goband.common.UserSessionUtils;
import com.example.goband.model.User;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-06-01
 * Time: 20:27
 */
@RestController
public class UserAPI {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest request,String username, String password) {
        //1、非空校验
        if(!StringUtils.hasLength(username) && !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"非法请求");
        }

        User user = userService.selectByName(username);

        //用户名有效
        if(user != null && user.getUserId() > 0) {
            //判断密码是否相同
            if(PasswordUtils.check(password,user.getPassword())) {
                //登录成功,将User信息存储到session会话
                HttpSession session = request.getSession(true);

                session.setAttribute(AppVariable.USER_SESSION_KEY,user);
                user.setPassword(""); //隐藏敏感信息
                //后台日志
                System.out.println("[login] username=" + username);
                return AjaxResult.success(user);
            }
        }
        //用户名或密码无效
        return AjaxResult.fail(-1,"登录失败");
    }

    @PostMapping ("/register")
    public AjaxResult register(User user) {
        //非空校验
        if(user.getUsername() != null && StringUtils.hasLength(user.getUsername())
        && StringUtils.hasLength(user.getPassword())) {
            String password = PasswordUtils.encrypt(user.getPassword());
            user.setPassword(password);
            return AjaxResult.success(userService.insert(user));
        } else {
            return AjaxResult.fail(-1,"非法参数");
        }
    }

    @GetMapping("/userInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) {

        //1、从当前session中获取user信息
        User user = UserSessionUtils.getUserBySession(request);
        if(user == null) {
            return AjaxResult.fail(-1,"非法请求");
        }

        //大厅需要实时获取用户信息
        User newUser = userService.selectByName(user.getUsername());

        return AjaxResult.success(newUser);
    }
}
